﻿using System;
using System.Configuration;
using System.Reflection;
using EPiServer;
using EPiServer.BaseLibrary;
using EPiServer.Configuration;
using EPiServer.Enterprise;
using EPiServer.Implementation;
using EPiServer.Web;
using EPiServer.Web.Hosting;
using System.IO;
using EPiServer.DataAccess;
using EPiServer.Core;

namespace EPiSugar.UnitTesting
{
    public class ShortCircuit : IDisposable
    {

        public IDisposable InitializeFromConfiguration()
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            GenericHostingEnvironment.Instance = new FakeHostingEnvironment { ApplicationVirtualPath = "/", ApplicationPhysicalPath = Environment.CurrentDirectory };
            Global.BaseDirectory = Environment.CurrentDirectory;

            var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            EPiServerSection.CurrentConfiguration = configuration;

            if (configuration.ConnectionStrings.ConnectionStrings.Count == 0) throw new ApplicationException("Did not find any connection strings in the connectionStrings section.");
            if (configuration.Sections["episerver"] == null) throw new ApplicationException("Did not find an episerver configuration section.");

            DataAccessBase.ConnectionSettings = configuration.ConnectionStrings.ConnectionStrings[0];
            DataAccessBase.DatabaseFactory = new SqlDatabaseFactory(DataAccessBase.ConnectionSettings);
            Settings.InitializeAllSettings(EPiServerSection.CurrentConfiguration);
            Settings.Instance = EPiServerSection.Instance.Sites[0].SiteSettings;
            
            LanguageManager.Instance = new LanguageManager();
            InitializationModule.Initialize(EPiServerSection.Instance, Settings.Instance);

            return this;
        }

        //public IDisposable Initialize(string connectionString)
        //{
        //    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        //    GenericHostingEnvironment.Instance = new FakeHostingEnvironment { ApplicationVirtualPath = "/", ApplicationPhysicalPath = Environment.CurrentDirectory };
        //    Global.BaseDirectory = Environment.CurrentDirectory;
            
        //    var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        //    EPiServerSection.CurrentConfiguration = configuration;
        //    if (configuration.ConnectionStrings.ConnectionStrings.Count == 0)
        //        configuration.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("EPiServerDB", connectionString, "System.Data.SqlClient"));
        //    if(configuration.Sections["episerver"] == null)
        //        configuration.Sections.Add("episerver", new FakeEPiServerSection());
        //    DataAccessBase.ConnectionSettings = configuration.ConnectionStrings.ConnectionStrings[0];
        //    DataAccessBase.DatabaseFactory = new SqlDatabaseFactory(DataAccessBase.ConnectionSettings);
        //    Settings.InitializeAllSettings(EPiServerSection.CurrentConfiguration);
        //    Settings.Instance = EPiServerSection.Instance.Sites[0].SiteSettings;
        //    var i = DataAccessBase.IsOracle;
        //    LanguageManager.Instance = new LanguageManager();
        //    InitializationModule.Initialize(EPiServerSection.Instance, Settings.Instance);

        //    return this;
        //}

        Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            switch (args.Name.Split(new[] { ',' })[0].Trim())
            {
                case "EPiServer": return typeof(Global).Assembly;
                case "EPiServer.Configuration": return typeof(Settings).Assembly;
                case "EPiServer.BaseLibrary": return typeof(ClassFactory).Assembly; 
                case "EPiServer.Implementation": return typeof(SimpleClassFactory).Assembly;
                case "EPiServer.Enterprise": return typeof(SetUp).Assembly;
            }
            return null;
        }

        public void Dispose()
        {
            InitializationModule.Uninitialize();
            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
        }

        public static void EnsureConfiguration()
        {
            if(!File.Exists("license.config"))
            {
                string message = string.Format("Could not locate license.config in the directory '{0}'. You should include a license file in your project and set it's 'Copy to output directory' property to 'Copy always'.", Environment.CurrentDirectory);
                throw new ApplicationException(message);
            }
            if(ConfigurationManager.GetSection("episerver") == null)
            {
                string message = "Could not locate the 'episerver' configuration section in the app configuration. You should add an App.config file and insert the episerver configuration section handler.";
                throw new ApplicationException(message);
            }
        }
    }
}
